<!--
 * @Descripttion:
 * @version:
 * @Author: hhy
 * @Date: 2021-04-21 17:52:18
 * @LastEditors: hhy
 * @LastEditTime: 2021-05-17 16:12:22
 * @FilePath: \votemp-user-pc\src\views\components\actList\act-clear-data.vue
-->
<template>
  <div class="add-role">
    <el-form
      ref="administratorFormRef"
      :model="form"
      :rules="rules"
      class="act-clear-from"
      labelWidth="120px"
    >
      <el-form-item label="角色名称：" prop="roleName">
        <el-col :span="6">
          <el-input v-model.trim="form.roleName" size="large" />
        </el-col>
      </el-form-item>
      <el-form-item label="角色描述：" prop="remark">
        <el-col :span="6">
          <el-input
            type="textarea"
            rows="5"
            v-model.trim="form.remark"
            size="large"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="状态：">
        <el-switch
          v-model="form.status"
          size="large"
          inline-prompt
          active-text="启用"
          inactive-text="禁用"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
      <el-form-item label="菜单权限:">
        <el-tree
          ref="treemenu"
          :data="RoleResourceList"
          :props="defaultProps"
          :default-checked-keys="menuLists"
          empty-text=""
          show-checkbox
          node-key="menuId"
          @check-change="handleCheckChange"
        >
        </el-tree>
      </el-form-item>
      <el-form-item>
        <el-button @click="$router.go(-1)">取消</el-button>
        <el-button type="primary" @click="onConfirm(administratorFormRef)">
          确定
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { defineComponent, toRefs, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { baseMsg } from "@/utils/utils";
import { getMenu } from "@/api/login";
import { GetRoleInfo, AddRole, UpdateRole } from "@/api/system";
export default defineComponent({
  emits: ["confirm", "close"],
  setup() {
    const route = useRoute();
    const router = useRouter();
    const administratorFormRef = ref(null);
    const state = reactive({
      rules: {
        roleName: [
          {
            required: true,
            message: "请输入角色名称",
            trigger: "blur",
          },
        ],
      },
      form: {
        roleName: "",
        remark: "",
        status: 0,
        authMenu: [],
      },
      // 所有菜单
      RoleResourceList: [],
      // 树状图prop
      defaultProps: {
        children: "children",
        label: "menuName",
        id: "menuId",
      },
      // 默认选中
      menuLists: [],
      // 选中的id集合
      menuIds: [],
    });
    // 选中后操作
    const treemenu = ref(null);
    const handleCheckChange = () => {
      const res = treemenu.value
        .getCheckedKeys()
        .concat(treemenu.value.getHalfCheckedKeys());
      state.menuIds = res;
    };
    // 初始化菜单
    const menuListMap = (list) => {
      for (let i = 0; i < list.length; i++) {
        if (list[i].children.length > 0) {
          for (let j = 0; j < list[i].children.length; j++) {
            if (list[i].children[j].children.length > 0) {
              for (let k = 0; k < list[i].children[j].children.length; k++) {
                list[i].children[j].children[k].authed = false;
              }
            }
            list[i].children[j].authed = false;
          }
        }
        list[i].authed = false;
      }
    };
    // 设置菜单authed
    const authedSet = (list) => {
      state.menuIds.map((item) => {
        for (let i = 0; i < list.length; i++) {
          if (list[i].children.length > 0) {
            for (let j = 0; j < list[i].children.length; j++) {
              if (list[i].children[j].children.length > 0) {
                for (
                  let k = 0;
                  k < list[i].children[j].children[k].length;
                  k++
                ) {
                  if (list[i].children[j].children[k].menuId == item) {
                    list[i].children[j].children[k].authed = true;
                  }
                }
              }
              if (list[i].children[j].menuId == item) {
                list[i].children[j].authed = true;
              }
            }
          }
          if (list[i].menuId == item) {
            list[i].authed = true;
          }
        }
      });
    };
    // 获取菜单中authed为true的menuId
    const getMenuId = (list) => {
      for (let i = 0; i < list.length; i++) {
        if (list[i].children.length > 0) {
          for (let j = 0; j < list[i].children.length; j++) {
            if (list[i].children[j].children.length > 0) {
              for (let k = 0; k < list[i].children[j].children[k].length; k++) {
                if (list[i].children[j].children[k].authed == true) {
                  state.menuIds.push(list[i].children[j].children[k].menuId);
                }
              }
            }
            if (list[i].children[j].authed == true) {
              state.menuIds.push(list[i].children[j].menuId);
            }
          }
        }
        if (list[i].authed == true && list[i].children.length < 1) {
          state.menuIds.push(list[i].menuId);
        }
      }
    };

    const init = async () => {
      const res = await getMenu();
      if (res.code === 4201) {
        state.RoleResourceList = res.data;
      }
      if (route.query.type == "edit") {
        GetRoleInfo({
          id: route.query.id,
        }).then((res) => {
          if (res.code == 4201) {
            state.form = {
              ...res.data,
            };
            getMenuId(state.form.authMenu);
            // 菜单回显
            treemenu.value.setCheckedKeys(state.menuIds);
          }
        });
      }
    };
    init();

    const onConfirm = async (formEl) => {
      if (!formEl) return;
      await formEl.validate(async (valid, fields) => {
        if (valid) {
          if (state.menuIds.length > 0) {
            authedSet(state.RoleResourceList);
            state.form.authMenu = state.RoleResourceList;
          }
          if (route.query.type == "edit") {
            menuListMap(state.RoleResourceList);
            authedSet(state.RoleResourceList);
            state.form.authMenu = state.RoleResourceList;
            const res = await UpdateRole(state.form);
            if (res.code == 4201 || res.code == 4202) {
              baseMsg("编辑成功");
              router.go(-1);
            } else {
              baseMsg("编辑失败", false);
            }
          } else {
            const res = await AddRole(state.form);
            if (res.code == 4202) {
              baseMsg("添加成功");
              router.go(-1);
            } else {
              baseMsg("添加失败", false);
            }
          }
        } else {
          return;
        }
      });
    };

    return {
      ...toRefs(state),
      onConfirm,
      administratorFormRef,
      handleCheckChange,
      treemenu,
    };
  },
});
</script>
<style lang="scss">
.add-role {
  padding: 20px;
}
</style>
